<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="时间范围" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>


      <el-form-item label="优先级" prop="assetCategory">
        <el-select
          v-model="queryParams.priorityLevel"
          placeholder="请选择优先级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.OA_PRIORITY_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:schedule-arrangement:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:schedule-arrangement:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">

      <el-table-column label="优先级" align="center" prop="priorityLevel">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_PRIORITY_STATUS" :value="scope.row.priorityLevel" />
        </template>
      </el-table-column>

      <el-table-column label="日程时间范围" align="center" prop="scheduleTimeRange" />
      <el-table-column label="日程内容" align="center" prop="scheduleContent" />
      <el-table-column label="提醒时间" align="center" prop="reminderTime">
        <template #default="scope">
          <span>{{ formatReminderTime(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:schedule-arrangement:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:schedule-arrangement:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ScheduleArrangementForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleArrangementApi, ScheduleArrangementVO } from '@/api/oa/schedulearrangement'
import ScheduleArrangementForm from './ScheduleArrangementForm.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 日程安排 列表 */
defineOptions({ name: 'ScheduleArrangement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ScheduleArrangementVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  scheduleTimeRange: undefined,
  startTime: undefined,
  endTime: undefined,
  scheduleContent: undefined,
  priorityLevel: undefined,
  reminderSetting: undefined,
  scheduleDescription: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async (params = {
  pageNo: queryParams.pageNo,
  pageSize: queryParams.pageSize,
  startTime: undefined,
  endTime: undefined,
  priorityLevel: queryParams.priorityLevel,
  scheduleContent: queryParams.scheduleContent
}) => {
  loading.value = true;
  try {
    const data = await ScheduleArrangementApi.getScheduleArrangementPage(params);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

function formatDateTime(date: Date | string | number, format = 'YYYY-MM-DD HH:mm'): string {
  const dt = new Date(date)
  const pad = (n: number) => n.toString().padStart(2, '0')

  const year = dt.getFullYear()
  const month = pad(dt.getMonth() + 1)
  const day = pad(dt.getDate())
  const hours = pad(dt.getHours())
  const minutes = pad(dt.getMinutes())
  const seconds = pad(dt.getSeconds())

  return format
    .replace('YYYY', year.toString())
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

const formatReminderTime = (row: ScheduleArrangementVO): string => {
  // 如果 reminderSetting 为 0，表示不提醒
  if (row.reminderSetting === 0) {
    return '-'
  }

  // 如果缺少必要的数据，返回默认值
  if (!row.startTime || row.reminderSetting === undefined || row.reminderSetting === null) {
    return '-'
  }

  try {
    // 计算提醒时间：startTime - reminderSetting（分钟）
    const reminderTimestamp = row.startTime - (row.reminderSetting * 60 * 1000)
    const reminderDate = new Date(reminderTimestamp)

    // 格式化为 YYYY-MM-DD HH:mm 格式
    return formatDateTime(reminderDate, 'YYYY-MM-DD HH:mm')
  } catch (error) {
    console.error('计算提醒时间出错:', error)
    return '-'
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;

  let startTimeParam = undefined;
  let endTimeParam = undefined;

  if (queryParams.startTime && queryParams.startTime.length >= 2) {
    startTimeParam = queryParams.startTime[0];
    endTimeParam = queryParams.startTime[1];
  }

  // 构造新的请求参数对象，避免携带原始数组
  const requestParams = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    priorityLevel: queryParams.priorityLevel,
    scheduleContent: queryParams.scheduleContent,
    startTime: startTimeParam,
    endTime: endTimeParam
  };

  getList(requestParams);
};


/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ScheduleArrangementApi.deleteScheduleArrangement(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ScheduleArrangementApi.exportScheduleArrangement(queryParams)
    download.excel(data, '日程安排.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
